package com.guaju.yueshangLife.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.githang.statusbar.StatusBarCompat;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.base.MyAppcomActivity;
import com.guaju.yueshangLife.bean.AlipayBean;
import com.guaju.yueshangLife.dao.SearchHistoryModel;
import com.guaju.yueshangLife.databinding.ActivityOrderPaySelectMethodBinding;
import com.guaju.yueshangLife.databinding.DialogCommonBinding;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.DateUtils;
import com.zhy.autolayout.utils.L;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.util.Map;

public class OrderPaySelectMethodActivity extends MyAppcomActivity {
    public static final String ORDER_ID = "order_id";
    public static final String CANCLE_AT = "cancle_at";
    public static final String TOTAL_MONEY = "total_money";
    public static final String PAY_METHOD = "pay_method";
    private static final int SDK_PAY_FLAG = 666;
    private static int COUNT_TIME = 600;

    private ActivityOrderPaySelectMethodBinding binding;
    AlertDialog alertDialog;
    private AlertDialog limitDialog;
    private String total_money;
    private long cancleAt;
    private int orderId;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (COUNT_TIME == what) {
                if (distanceLong > 1) {
                    distanceLong--;
                    String distance = DateUtils.getDistance(distanceLong);
                    binding.tvOrderLasttime.setText(distance);
                } else {
                    binding.tvOrderLasttime.setText("订单超时");
                }

                mHandler.sendEmptyMessageDelayed(COUNT_TIME, 1000);
            } else if (SDK_PAY_FLAG == what) {
                //这里接收支付宝的回调信息
                //需要注意的是，支付结果一定要调用自己的服务端来确定，不能通过支付宝的回调结果来判断
            }
        }
    };
    private long distanceLong;
    private String payMehod;
    private String orderInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_pay_select_method);
        EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));
        initView();
        initListener();
        initData();
    }

    private void initListener() {
        View fl_back = binding.top.findViewById(R.id.fl_back);
        fl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                DialogCommonBinding dialogCommonBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_common, null, false);
                dialogCommonBinding.dialogTitle.setText("确认离开");
                dialogCommonBinding.dialogMsg.setText("下单30分钟后未完成支付，订单将被取消，请您尽快支付");
                dialogCommonBinding.dialogCancel.setText("确认离开");
                dialogCommonBinding.dialogConfirm.setText("继续支付");
                dialogCommonBinding.dialogConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BaseApplication.getLiteOrm().delete(SearchHistoryModel.class);
                        alertDialog.hide();
                        //TODO 支付

                    }
                });
                dialogCommonBinding.dialogCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.hide();
                        finish();
                    }
                });
                builder.setView(dialogCommonBinding.getRoot());
                alertDialog = builder.create();
                alertDialog.show();
            }
        });

        binding.llPayLimit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                limitDialog = showCommentDailog(R.layout.dialog_pay_limit_info);
            }
        });

        binding.rlWechatpay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.rbWechatpay.setChecked(true);
                binding.rbAlipay.setChecked(false);
            }
        });

        binding.rlAlipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.rbAlipay.setChecked(true);
                binding.rbWechatpay.setChecked(false);
            }
        });


    }

    private void initView() {
        TextView top_tv_title = binding.top.findViewById(R.id.top_tv_title);
        top_tv_title.setText("订单支付");

    }

    private void initData() {
        int timeLasts;
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (intent.hasExtra(TOTAL_MONEY)) {
            total_money = extras.getString(TOTAL_MONEY);
        }
        if (intent.hasExtra(CANCLE_AT)) {
            cancleAt = extras.getLong(CANCLE_AT);
        }
        if (intent.hasExtra(ORDER_ID)) {
            orderId = extras.getInt(ORDER_ID);
        }
        if (intent.hasExtra(PAY_METHOD)) {
            payMehod = extras.getString(PAY_METHOD);
        }
        binding.tvPayTotalAmount.setText("¥" + total_money);
        binding.btSkipTopay.setText("去支付 ¥" + total_money);
        long now = System.currentTimeMillis() / 1000;
        distanceLong = cancleAt - now;
        if (distanceLong > 0) {
            String distance = DateUtils.getDistance(distanceLong);
            binding.tvOrderLasttime.setText(distance);
            mHandler.sendEmptyMessage(COUNT_TIME);
        } else {
            binding.tvOrderLasttime.setText("订单超时");
        }

        if (TextUtils.equals("支付宝", payMehod)) {
            binding.rbAlipay.setChecked(true);
        } else {
            binding.rbWechatpay.setChecked(true);
        }

        binding.btSkipTopay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiEntity.alipay(orderId,"123456");
            }
        });
    }


    /**
     * 弹出评论框
     */
    private AlertDialog showCommentDailog(int resId) {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.BottomDialog).create();
        View view = View.inflate(this, resId, null);
        view.setBackgroundColor(Color.parseColor("#FFFFFF"));
        FrameLayout fl_close = view.findViewById(R.id.fl_close);
        fl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                limitDialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        //window.setWindowAnimations(R.style.dialogStyle);
//        window.getDecorView().setPadding(0, 0, 0, 0);

        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        window.setContentView(view);

        //获得window窗口的属性
        WindowManager.LayoutParams params = window.getAttributes();
        //设置窗口宽度为充满全屏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉
        //设置窗口高度为包裹内容
        params.height = getResources().getDimensionPixelOffset(R.dimen.bottom_dialog_height);
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f;//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params);
        return dialog;
    }


    public void topay() {
        //下面的orderInfo就是咱自己的服务端返回的订单信息，里面除了订单ID等，还有签名等安全信息
        //使用方式基本按照支付宝的DEMO里面就行了
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderPaySelectMethodActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.e("guajujerry", "run: " + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipayBack(AlipayBean bean) {
        if (null != bean) {
            AlipayBean.DataBean data = bean.getData();
            if (data != null) {
                orderInfo = data.getCode();
                topay();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
